
let writeFn = null;

function randomStringFn(length, letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') {
  length || (length = 8);
  const numbers = '0123456789';
  // const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  let total = '';
  total = numbers + letters;
  let result = '';

  while (length > 0) {
    length--;
    result += total[Math.floor(Math.random() * total.length)];
  }

  return result;
};

function initMqttFn(options = {}) {
  const mqtt = require('./../node/mqtt/index');

  const {
    host = null,
    port = null,
    clientId = null,
    username = null,
    password = null
  } = options;

  if (!(host && port && clientId && username && password)) {
    throw new Error('请传入正确的配置参数');
  }

  const url = 'mqtt://' + host + ':' + port; //服务器地址+端口

  const subTopic =
    'dfd/v3/' +
    clientId.slice(0, 16) +
    '/' +
    clientId.slice(17, 33) +
    '/scribe';

  const pubTopic =
    'dfd/v3/' +
    clientId.slice(0, 16) +
    '/' +
    clientId.slice(17, 33) +
    '/publish';

  const client = initFn();

  const device = {
    projectId: clientId.slice(0, 16),
    deviceId: clientId.slice(17, 33),
    subTopic: subTopic,
    pubTopic: pubTopic,
    client
  };

  function initFn() {
    const client = mqtt.connect(url, {
      clientId,
      username,
      password
    });

    client.on('connect', function () {
      console.log('MQTT已连接');
      if (client.subscribe(subTopic).connected == true) {
        console.log('订阅成功');

        process.send({
          type: 'isOnline',
          success: true,
          name: 'mqtt'
        });
      }
    });

    client.on('message', function (_topic, msg) {
      const message = JSON.parse(msg);
      console.log(message);
      switch (message.method) {
        case 'platform.down':
          deviceResPlatform(message);
          break;
        case 'device.report_reply':
          console.log('device.report_reply');
          break;
        default:
          console.log('device.report_reply');
          break;
      }
    });

    return client;
  }

  function deviceResPlatform(message={}) {
    switch (message?.params?.cmd) {
      case 'set':
        // deviceResPlatformSet(device, message);
        break;
      case 'get':
        // deviceResPlatformGet(device, message);
        break;
      default:
        console.log(message.params.cmd);
        break;
    }
  }

  function uploadMessageFn(uploadOptions = {}) {
    const { pubTopic = null } = device;

    const {
      cmd = 'post',
      moduleMark = 'ModuleJSON',
      version = '1.0',
      data = null,
      method = 'device.report'
    } = uploadOptions;

    console.log(uploadOptions);

    const paylaod = {
      method,
      params: {
        cmd,
        moduleMark,
        data
      },
      messageId: randomStringFn(12),
      version,
      time: new Date().getTime()
    };

    client.publish(pubTopic, JSON.stringify(paylaod));

    console.log('上传mqtt数据', paylaod);
  }

  return {
    uploadMessageFn,
    client,
    device
  };
}

process.on('message', obj => {
  if (obj) {
    const { type = null, options = null ,data=null} = obj;

    switch (type) {
      case 'init':
        const { uploadMessageFn =null} = initMqttFn(options);

        writeFn = uploadMessageFn;
        break;

      case 'write':
        writeFn && writeFn(data);
        break;

      default:
        break;
    }
  }
});

process.on('message', obj => {
  if (obj) {
    const { type = null, data = null } = obj;

    switch (type) {
      case 'delete':
        process.exit();
        break;

      default:
        break;
    }
  }
});